<template>
<div class="message-container">
    <!-- 顶部标题栏 -->
    <div class="message-header">
        <div class="header-title">消息</div>
        <!-- <div class="header-action" @click="goToGroupChat">
            <van-icon name="friends-o" size="20" />
            <span>发现群聊</span>
        </div> -->
    </div>

    <!-- 下拉刷新 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" success-text="刷新成功">
        <!-- 消息类型图标 -->
        <div class="message-types">
            <div class="type-item" @click="goToMessageType('likes')">
                <div class="type-icon like-icon">
                    <van-icon name="like" size="24" />
                    <div class="badge" v-if="unreadCounts.likes > 0">{{ unreadCounts.likes }}</div>
                </div>
                <div class="type-name">赞和收藏</div>
            </div>
            <div class="type-item" @click="goToMessageType('follows')">
                <div class="type-icon follow-icon">
                    <van-icon name="friends" size="24" />
                    <div class="badge" v-if="unreadCounts.follows > 0">{{ unreadCounts.follows }}</div>
                </div>
                <div class="type-name">新增关注</div>
            </div>
            <div class="type-item" @click="goToMessageType('comments')">
                <div class="type-icon comment-icon">
                    <van-icon name="chat" size="24" />
                    <div class="badge" v-if="unreadCounts.comments > 0">{{ unreadCounts.comments }}</div>
                </div>
                <div class="type-name">评论和@</div>
            </div>
            <div class="type-item" @click="goToMessageType('system')">
                <div class="type-icon system-icon">
                    <van-icon name="bell" size="24" />
                    <div class="badge" v-if="unreadCounts.system > 0">{{ unreadCounts.system }}</div>
                </div>
                <div class="type-name">系统通知</div>
            </div>
        </div>

        <!-- 消息列表 -->
        <div class="message-list">
            <!-- 加载状态 -->
            <div class="loading-container" v-if="loading">
                <van-loading type="spinner" color="#ff2442" />
            </div>

            <!-- 无消息状态 -->
            <div class="empty-state" v-else-if="isEmpty">
                <van-empty image="search" description="暂无消息" />
            </div>

            <!-- 聊天消息内容 -->
            <template v-else>
                <!-- 群聊消息 -->
                <div class="message-item" v-for="(item) in groupMessages" :key="'group-' + item.id"
                    @click="openChat(item)">
                    <div class="message-avatar">
                        <div class="group-avatar">
                            <img v-for="(avatar, i) in item.avatars.slice(0, 3)" :key="i" :src="avatar"
                                :alt="item.name" />
                        </div>
                        <div class="user-badge" v-if="item.unreadCount">{{ item.unreadCount }}</div>
                    </div>
                    <div class="message-content">
                        <div class="message-title">
                            <span class="message-name">{{ item.name }}</span>
                            <span class="message-time">{{ formatTime(item.time) }}</span>
                        </div>
                        <div class="message-preview">
                            <span class="message-sender" v-if="item.lastSender">{{ item.lastSender }}:</span>
                            <span class="message-text">{{ item.lastMessage }}</span>
                            <van-icon name="volume-o" v-if="item.muted" class="muted-icon" />
                        </div>
                    </div>
                    <div class="message-actions" @click.stop>
                        <van-icon name="more-o" size="18" @click="viewChatDetail(item, $event)" />
                    </div>
                </div>

                <!-- 个人消息 -->
                <div class="message-item" v-for="(item) in userMessages" :key="'user-' + item.id"
                    @click="openChat(item)">
                    <div class="message-avatar">
                        <img :src="item.avatar" :alt="item.name" />
                        <div class="user-badge" v-if="item.unreadCount">{{ item.unreadCount }}</div>
                    </div>
                    <div class="message-content">
                        <div class="message-title">
                            <span class="message-name">{{ item.name }}</span>
                            <span class="message-time">{{ formatTime(item.time) }}</span>
                        </div>
                        <div class="message-preview">
                            <span class="message-text">{{ item.lastMessage }}</span>
                            <van-icon name="volume-o" v-if="item.muted" class="muted-icon" />
                        </div>
                    </div>
                    <div class="message-actions" @click.stop>
                        <van-icon name="more-o" size="18" @click="viewChatDetail(item, $event)" />
                    </div>
                </div>

                <!-- 系统消息 -->
                <div class="message-item system-message" v-for="(item) in systemMessages" :key="'system-' + item.id"
                    @click="openSystemMessage(item)">
                    <div class="message-avatar system-avatar">
                        <van-icon :name="item.icon" size="24" />
                    </div>
                    <div class="message-content">
                        <div class="message-title">
                            <span class="message-name">{{ item.title }}</span>
                            <span class="message-time">{{ formatTime(item.time) }}</span>
                        </div>
                        <div class="message-preview">
                            <span class="message-text">{{ item.content }}</span>
                        </div>
                    </div>
                    <div class="message-actions" @click.stop>
                        <van-icon name="delete-o" size="18" @click.stop="deleteSystemMessage(item)" />
                    </div>
                </div>
            </template>
        </div>
    </van-pull-refresh>

    <!-- 操作菜单 -->
    <van-action-sheet v-model="showActionSheet" :actions="actionSheetActions" cancel-text="取消"
        @select="onActionSelect" />
</div>
</template>

<script>
import { defineComponent } from 'vue'
import { mapGetters } from 'vuex'
import { Toast, Dialog } from 'vant'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import { messageApi } from '@/api/message'

// 配置dayjs使用相对时间插件
dayjs.extend(relativeTime)

export default defineComponent({
    name: 'MessagePage',
    data() {
        return {
            // 加载状态
            loading: false,
            // 下拉刷新状态
            refreshing: false,
            // 操作菜单显示状态
            showActionSheet: false,
            // 操作菜单选项
            actionSheetActions: [],
            // 当前操作的消息
            currentMessage: null,
            // 未读消息计数
            unreadCounts: {
                likes: 2,
                comments: 1,
                follows: 3,
                system: 1
            },
            // 群聊消息
            groupMessages: [
                {
                    id: 'g1',
                    name: '【群聊】没想好名字',
                    avatars: [
                        'https://img01.yzcdn.cn/vant/cat.jpeg',
                        'https://img01.yzcdn.cn/vant/dog.jpeg',
                        'https://img01.yzcdn.cn/vant/apple-1.jpg'
                    ],
                    lastSender: 'momo',
                    lastMessage: '[笔记] 小猫',
                    time: '2023-05-10 16:52',
                    unreadCount: 0,
                    muted: false
                },
                {
                    id: 'g2',
                    name: 'cursor 实践哒哒哒',
                    avatars: [
                        'https://img01.yzcdn.cn/vant/cat.jpeg',
                        'https://img01.yzcdn.cn/vant/dog.jpeg'
                    ],
                    lastMessage: '是原王哒～流光卡片：之前真名其妙被禁...',
                    time: '2023-05-10 12:52',
                    unreadCount: 0,
                    muted: false
                }
            ],
            // 个人消息
            userMessages: [
                {
                    id: 'u1',
                    name: 'momo',
                    avatar: 'https://img01.yzcdn.cn/vant/cat.jpeg',
                    lastMessage: '我们已相互关注，开始聊天吧🎂',
                    time: '星期一',
                    unreadCount: 0,
                    muted: false
                },
                {
                    id: 'u2',
                    name: '悟空',
                    avatar: 'https://img01.yzcdn.cn/vant/monkey.jpeg',
                    lastMessage: '我们已相互关注，开始聊天吧🎂',
                    time: '星期一',
                    unreadCount: 0,
                    muted: false
                },
                {
                    id: 'u3',
                    name: 'momo',
                    avatar: 'https://img01.yzcdn.cn/vant/cat.jpeg',
                    lastMessage: '[卡片] 没想好名字',
                    time: '星期四',
                    unreadCount: 0,
                    muted: false
                }
            ],
            // 系统消息
            systemMessages: [
                {
                    id: 's1',
                    title: '系统消息',
                    icon: 'bell',
                    content: '账号违规提示',
                    time: '昨天',
                    isRead: false,
                    link: '/system/notice/1'
                },
                {
                    id: 's2',
                    title: '活动消息',
                    icon: 'gift-o',
                    content: '最后3天，百万奖金，错过等一年！',
                    time: '星期一',
                    isRead: true,
                    link: '/activity/1'
                }
            ]
        }
    },
    computed: {
        ...mapGetters(['user', 'isLogin']),

        // 计算是否没有消息
        isEmpty() {
            return (
                this.groupMessages.length === 0 &&
                this.userMessages.length === 0 &&
                this.systemMessages.length === 0
            )
        },

        // 计算总未读消息数
        totalUnreadCount() {
            // 聊天消息未读数
            const chatUnreadCount = this.groupMessages.reduce((sum, item) => sum + (item.unreadCount || 0), 0) +
                this.userMessages.reduce((sum, item) => sum + (item.unreadCount || 0), 0);

            // 其他类型消息未读数
            const otherUnreadCount = Object.values(this.unreadCounts).reduce((sum, count) => sum + count, 0);

            return chatUnreadCount + otherUnreadCount;
        }
    },
    created() {
        // 初始化数据
        this.initData()
    },
    methods: {
        // 处理WebSocket消息
        handleWebSocketMessage(message) {
            // 处理新消息通知
            if (message.type === 'chat' && !message.isSelf) {
                // 播放提示音或显示通知
                this.showMessageNotification(message)
            }
        },

        // 显示新消息通知
        showMessageNotification(message) {
            // 如果不是当前聊天窗口，显示通知
            if (this.$store.getters.currentChatSession !== message.from) {
                this.$notify({
                    message: `${message.sender || '新消息'}: ${message.content}`,
                    duration: 3000,
                    onClick: () => {
                        // 点击通知跳转到聊天页面
                        this.openChat({
                            id: message.from,
                            userId: message.from,
                            name: message.sender,
                            avatar: message.avatar
                        })
                    }
                })
            }
        },

        // 刷新消息列表
        onRefresh() {
            // 更新聊天会话列表
            this.userMessages = this.$store.getters.chatSessions.map(session => {
                return {
                    id: session.userId,
                    userId: session.userId,
                    name: session.name || '用户' + session.userId,
                    avatar: session.avatar || 'https://img01.yzcdn.cn/vant/cat.jpeg',
                    lastMessage: session.lastMessage,
                    time: new Date(session.lastTime),
                    unreadCount: session.unreadCount || 0
                }
            })

            setTimeout(() => {
                this.refreshing = false
                Toast('刷新成功')
            }, 1000)
        },

        // 初始化数据
        async initData() {
            this.loading = true
            try {
                // 获取未读消息数量
                await this.getUnreadCount()

                // 获取消息数据
                await this.getChatMessages()

                // 获取系统消息
                await this.getSystemMessages()
            } catch (error) {
                console.error('初始化数据失败', error)
                Toast('获取消息数据失败，请重试')
            } finally {
                this.loading = false
            }
        },

        // 获取未读消息数量
        async getUnreadCount() {
            try {
                // const data = await messageApi.getUnreadCount()
                // 模拟未读消息数据
                this.unreadCounts = {
                    likes: 2,
                    comments: 1,
                    follows: 3,
                    system: 1
                }

                // 更新Vuex中的通知数量
                this.$store.commit('setNotifications', this.totalUnreadCount)
            } catch (error) {
                console.error('获取未读消息数量失败', error)
            }
        },

        // 获取聊天消息
        async getChatMessages() {
            try {
                // 模拟API返回数据
                const data = {
                    code: 0,
                    message: "success",
                    data: {
                        groupMessages: [
                            {
                                id: 'g1',
                                name: '【群聊】没想好名字',
                                avatars: [
                                    'https://img01.yzcdn.cn/vant/cat.jpeg',
                                    'https://img01.yzcdn.cn/vant/dog.jpeg',
                                    'https://img01.yzcdn.cn/vant/apple-1.jpg'
                                ],
                                lastSender: 'momo',
                                lastMessage: '[笔记] 小猫',
                                time: '2023-05-10 16:52',
                                unreadCount: 0,
                                muted: false
                            },
                            {
                                id: 'g2',
                                name: 'cursor 实践哒哒哒',
                                avatars: [
                                    'https://img01.yzcdn.cn/vant/cat.jpeg',
                                    'https://img01.yzcdn.cn/vant/dog.jpeg'
                                ],
                                lastMessage: '是原王哒～流光卡片：之前真名其妙被禁...',
                                time: '2023-05-10 12:52',
                                unreadCount: 0,
                                muted: false
                            }
                        ],
                        userMessages: [
                            {
                                id: 'u1',
                                name: 'momo',
                                avatar: 'https://img01.yzcdn.cn/vant/cat.jpeg',
                                lastMessage: '我们已相互关注，开始聊天吧🎂',
                                time: '星期一',
                                unreadCount: 0,
                                muted: false
                            },
                            {
                                id: 'u2',
                                name: '悟空',
                                avatar: 'https://img01.yzcdn.cn/vant/monkey.jpeg',
                                lastMessage: '我们已相互关注，开始聊天吧🎂',
                                time: '星期一',
                                unreadCount: 0,
                                muted: false
                            },
                            {
                                id: 'u3',
                                name: 'momo',
                                avatar: 'https://img01.yzcdn.cn/vant/cat.jpeg',
                                lastMessage: '[卡片] 没想好名字',
                                time: '星期四',
                                unreadCount: 0,
                                muted: false
                            }
                        ],
                        total: 5,
                        hasMore: false
                    }
                }

                if (data && data.data) {
                    this.groupMessages = data.data.groupMessages || []
                    this.userMessages = data.data.userMessages || []
                }
            } catch (error) {
                console.error('获取聊天消息失败', error)
                throw error
            }
        },

        // 获取系统消息
        async getSystemMessages() {
            try {
                // 模拟API返回数据
                const data = {
                    code: 0,
                    message: "success",
                    data: {
                        list: [
                            {
                                id: 's1',
                                title: '系统消息',
                                icon: 'bell',
                                content: '账号违规提示',
                                time: '昨天',
                                isRead: false,
                                link: '/system/notice/1'
                            },
                            {
                                id: 's2',
                                title: '活动消息',
                                icon: 'gift-o',
                                content: '最后3天，百万奖金，错过等一年！',
                                time: '星期一',
                                isRead: true,
                                link: '/activity/1'
                            }
                        ],
                        hasMore: false
                    }
                }

                if (data && data.data && data.data.list) {
                    this.systemMessages = data.data.list
                } else {
                    this.systemMessages = []
                }
            } catch (error) {
                console.error('获取系统消息失败', error)
                throw error
            }
        },

        // 格式化时间
        formatTime(time) {
            if (!time) return ''

            const now = dayjs()
            const messageTime = dayjs(time)

            // 如果是今天
            if (now.isSame(messageTime, 'day')) {
                return messageTime.format('HH:mm')
            }

            // 如果是昨天
            if (now.subtract(1, 'day').isSame(messageTime, 'day')) {
                return '昨天 ' + messageTime.format('HH:mm')
            }

            // 如果是本周
            if (now.isSame(messageTime, 'week')) {
                const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
                return weekdays[messageTime.day()]
            }

            // 如果是今年
            if (now.isSame(messageTime, 'year')) {
                return messageTime.format('MM-DD')
            }

            // 其他情况
            return messageTime.format('YYYY-MM-DD')
        },

        // 下拉刷新
        async onRefresh() {
            try {
                // 重新获取数据
                await this.initData()
                Toast('刷新成功')
            } catch (error) {
                console.error('刷新失败', error)
                Toast('刷新失败')
            } finally {
                this.refreshing = false
            }
        },

        // 前往群聊发现页面
        goToGroupChat() {
            Toast('发现群聊功能开发中')
        },

        // 跳转到指定消息类型页面
        goToMessageType(type) {
            // 更新已读状态
            this.markTypeAsRead(type)

            // 根据类型跳转到统一消息页面
            this.$router.push(`/messages/${type}`)
        },

        // 标记指定类型消息为已读
        markTypeAsRead(type) {
            if (this.unreadCounts[type] > 0) {
                this.unreadCounts[type] = 0
                // 这里应该调用API将该类型的消息标记为已读
                // await messageApi.markAsRead({ type })

                // 更新Vuex中的通知数量
                this.$store.commit('setNotifications', this.totalUnreadCount)
            }
        },

        // 打开聊天页面
        async openChat(item) {
            // 标记消息为已读
            if (item.unreadCount > 0) {
                try {
                    await messageApi.markAsRead({ type: 'chat', id: item.id })
                    item.unreadCount = 0

                    // 更新Vuex中的通知数量
                    this.$store.commit('setNotifications', this.totalUnreadCount)
                } catch (error) {
                    console.error('标记已读失败', error)
                }
            }

            // 跳转到聊天页面
            this.$router.push(`/chat/${item.id}`)
        },

        // 查看聊天详情
        viewChatDetail(item, event) {
            event.stopPropagation()

            // 设置当前操作的消息
            this.currentMessage = item

            // 设置操作菜单选项
            this.actionSheetActions = [
                { name: '标记为已读', color: item.unreadCount > 0 ? '#1989fa' : '#999' },
                { name: item.muted ? '取消静音' : '静音', color: '#1989fa' },
                { name: '删除聊天', color: '#ee0a24' }
            ]

            // 显示操作菜单
            this.showActionSheet = true
        },

        // 操作菜单选择
        async onActionSelect(action) {
            if (!this.currentMessage) return

            if (action.name === '标记为已读') {
                if (this.currentMessage.unreadCount > 0) {
                    try {
                        await messageApi.markAsRead({ type: 'chat', id: this.currentMessage.id })
                        this.currentMessage.unreadCount = 0

                        // 更新Vuex中的通知数量
                        this.$store.commit('setNotifications', this.totalUnreadCount)

                        Toast('已标记为已读')
                    } catch (error) {
                        console.error('标记已读失败', error)
                        Toast('操作失败')
                    }
                }
            } else if (action.name === '静音') {
                // 实际项目中应该调用API设置静音
                this.currentMessage.muted = true
                Toast('已设置静音')
            } else if (action.name === '取消静音') {
                // 实际项目中应该调用API取消静音
                this.currentMessage.muted = false
                Toast('已取消静音')
            } else if (action.name === '删除聊天') {
                Dialog.confirm({
                    title: '删除聊天',
                    message: '确定要删除此聊天吗？'
                }).then(async () => {
                    try {
                        await messageApi.deleteMessage(this.currentMessage.id)

                        // 从列表中删除该消息
                        if (this.currentMessage.avatars) {
                            // 群聊消息
                            const index = this.groupMessages.findIndex(item => item.id === this.currentMessage.id)
                            if (index !== -1) {
                                this.groupMessages.splice(index, 1)
                            }
                        } else {
                            // 个人消息
                            const index = this.userMessages.findIndex(item => item.id === this.currentMessage.id)
                            if (index !== -1) {
                                this.userMessages.splice(index, 1)
                            }
                        }

                        Toast('已删除聊天')
                    } catch (error) {
                        console.error('删除聊天失败', error)
                        Toast('操作失败')
                    }
                }).catch(() => {
                    // 取消删除
                })
            }
        },

        // 打开系统消息
        async openSystemMessage(item) {
            // 标记系统消息为已读
            if (!item.isRead) {
                try {
                    await messageApi.markAsRead({ type: 'system', id: item.id })

                    // 更新消息状态
                    item.isRead = true

                    // 更新未读数量
                    this.unreadCounts.system = this.systemMessages.filter(msg => !msg.isRead).length

                    // 更新Vuex中的通知数量
                    this.$store.commit('setNotifications', this.totalUnreadCount)
                } catch (error) {
                    console.error('标记已读失败', error)
                }
            }

            // 如果有链接则跳转
            if (item.link) {
                this.$router.push(item.link)
            }
        },

        // 删除系统消息
        async deleteSystemMessage(item) {
            try {
                await messageApi.deleteMessage(item.id)

                // 从列表中删除该消息
                const index = this.systemMessages.findIndex(msg => msg.id === item.id)
                if (index !== -1) {
                    this.systemMessages.splice(index, 1)
                }

                // 如果消息未读，更新未读计数
                if (!item.isRead) {
                    this.unreadCounts.system--

                    // 更新Vuex中的通知数量
                    this.$store.commit('setNotifications', this.totalUnreadCount)
                }

                Toast('已删除消息')
            } catch (error) {
                console.error('删除消息失败', error)
                Toast('操作失败')
            }
        }
    }
})
</script>

<style scoped>
.message-container {
    min-height: 100vh;
    background-color: #f7f8fa;
    padding-bottom: 50px;
}

.message-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 16px;
    background-color: #fff;
}

.header-title {
    font-size: 18px;
    font-weight: 500;

}

.header-action {
    display: flex;
    align-items: center;
    color: #333;
    font-size: 14px;
}

.header-action .van-icon {
    margin-right: 4px;
}

.message-types {
    display: flex;
    justify-content: space-around;
    padding: 20px 0;
    background-color: #fff;
}

.type-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
}

.type-icon {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 8px;
    position: relative;
}

.like-icon {
    background-color: #ffecec;
    color: #ff6b6b;
}

.follow-icon {
    background-color: #e6f7ff;
    color: #1989fa;
}

.comment-icon {
    background-color: #e8faf0;
    color: #07c160;
}

.system-icon {
    background-color: #fff8e6;
    color: #ff9500;
}

.badge {
    position: absolute;
    top: -5px;
    right: -5px;
    min-width: 16px;
    height: 16px;
    border-radius: 8px;
    background-color: #ff2442;
    color: #fff;
    font-size: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 4px;
}

.type-name {
    font-size: 12px;
    color: #333;
}

.message-list {
    background-color: #fff;
    height: 100%;
}

.loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 40px 0;
}

.empty-state {
    padding: 40px 0;
}

.message-item {
    display: flex;
    padding: 12px 16px;
    border-bottom: 1px solid #f5f5f5;
}

.message-avatar {
    position: relative;
    width: 48px;
    height: 48px;
    margin-right: 12px;
    flex-shrink: 0;
}

.message-avatar img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    object-fit: cover;
}

.group-avatar {
    width: 100%;
    height: 100%;
    position: relative;
    border-radius: 8px;
    overflow: hidden;
    background-color: #f5f5f5;
}

.group-avatar img {
    position: absolute;
    width: 32px;
    height: 32px;
    object-fit: cover;
}

.group-avatar img:nth-child(1) {
    top: 0;
    left: 0;
}

.group-avatar img:nth-child(2) {
    top: 0;
    right: 0;
}

.group-avatar img:nth-child(3) {
    bottom: 0;
    left: 8px;
}

.user-badge {
    position: absolute;
    top: -5px;
    right: -5px;
    min-width: 16px;
    height: 16px;
    border-radius: 8px;
    background-color: #ff2442;
    color: #fff;
    font-size: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 4px;
}

.message-content {
    flex: 1;
    overflow: hidden;
}

.message-title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 4px;
}

.message-name {
    font-size: 15px;
    font-weight: 500;
    color: #333;
}

.message-time {
    font-size: 12px;
    color: #999;
}

.message-preview {
    display: flex;
    align-items: center;
    font-size: 13px;
    color: #666;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.message-sender {
    color: #333;
    margin-right: 4px;
}

.message-text {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
}

.muted-icon {
    margin-left: 4px;
    color: #999;
    flex-shrink: 0;
}

.system-avatar {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f0f9ff;
    border-radius: 50%;
    color: #1989fa;
}

.system-message .message-name {
    color: #333;
}

.message-actions {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
    margin-left: 12px;
    flex-shrink: 0;
    color: #999;
}

.message-actions .van-icon {
    padding: 5px;
}
</style>